<template>
  <ul class="xitongYonghu" style="z-index: 1">
    <li class="xitongYonghu-top">
      <ul class="xitong-search" style="padding: 10px;display: flex;justify-content: space-between;align-items: center;">
        <div class="operation-group">
          <el-button type="primary" @click="handleAdd">
            <el-icon><Plus /></el-icon>添加
          </el-button>
        </div>
      </ul>

      <!-- 添加收费标准对话框 -->
      <el-dialog v-model="dialogFormVisible" title="添加收费标准" width="30%">
        <el-form :model="form" label-width="100px">
          <el-form-item label="收费类型" required>
            <el-autocomplete
              v-model="form.chargeTypeName"
              :fetch-suggestions="querySearch"
              clearable
              class="inline-input w-full"
              placeholder="请选择或输入收费类型"
              @select="handleSelect"
            />
          </el-form-item>
          <el-form-item label="价格" required>
            <el-input-number
              v-model="form.price"
              :min="0"
              :precision="2"
              :step="10"
              placeholder="请输入价格"
            />
          </el-form-item>
        </el-form>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="dialogFormVisible = false">取消</el-button>
            <el-button type="primary" @click="addFee">确认添加</el-button>
          </div>
        </template>
      </el-dialog>

      <!-- 收费标准列表 -->
      <li>
        <el-table
          ref="tableRef"
          :data="itemsArr"
          style="width: 100%"
          border
          v-loading="isLoading"
        >
          <el-table-column prop="chargeTypeName" label="收费类型" min-width="200" />
          <el-table-column prop="price" label="价格" width="150">
            <template #default="scope">
              {{ scope.row.price }} 元
            </template>
          </el-table-column>
          <el-table-column label="操作" width="120" fixed="right">
            <template #default="scope">
              <el-button type="danger" size="small" @click="handleDelete(scope.row.chargeTypeId)">
                <el-icon><Delete /></el-icon>删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页器 -->
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[5, 10, 20]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          class="pagination"
        />
      </li>
    </li>
  </ul>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import axios from 'axios'
import { Plus, Delete } from '@element-plus/icons-vue'

// 收费类型选项相关数据
const feeOptions = ref([])

// 添加一个存储所有收费类型的变量
const allChargeTypes = ref([])

// 加载收费类型选项
const loadAllFees = async () => {
  try {
    const response = await axios.get('consultants/selectChargeStandardType2')
    if (response.data.code === 200) {
      console.log('收费类型数据:', response.data.data)
      // 保存完整的收费类型数据
      allChargeTypes.value = response.data.data
      // 处理下拉选择框的选项
      feeOptions.value = response.data.data.map(fee => ({
        value: fee.chargeTypeName,
        chargeTypeId: fee.chargeTypeId
      }))
      console.log('处理后的选项:', feeOptions.value)
    }
  } catch (error) {
    console.error('获取收费类型失败:', error)
    ElMessage.error('获取收费类型失败')
  }
}

// 搜索建议方法
const querySearch = (queryString, cb) => {
  const results = queryString
    ? feeOptions.value.filter(createFilter(queryString))
    : feeOptions.value
  cb(results)
}

// 创建过滤器
const createFilter = (queryString) => {
  return (fee) => {
    return fee.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0
  }
}

// 选择建议项处理
const handleSelect = (item) => {
  console.log('选中的项:', item)  // 调试日志
  form.value = {
    ...form.value,
    chargeTypeName: item.value,
    chargeTypeId: item.chargeTypeId  // 确保正确赋值chargeTypeId
  }
}

// 表单数据
const form = ref({
  chargeTypeId: '',
  chargeTypeName: '',
  price: '',
  consultantId: ''
})

// 基础数据
const dialogFormVisible = ref(false)
const isShow = ref(true)
const isLoading = ref(false)
const currentPage = ref(1)
const pageSize = ref(5)
const total = ref(0)
const itemsArr = ref([])
const tableRef = ref(null)
const isComponentUnmounted = ref(false)

// 获取收费标准列表
const getFeeList = async () => {
  if (isComponentUnmounted.value) return
  try {
    let user = sessionStorage.getItem('user')
    if (!user) {
      ElMessage.error('请先登录')
      return
    }
    user = JSON.parse(user)

    isLoading.value = true
    const response = await axios.get('consultants/selectAllFeeManagement', {
      params: {
        consultantId: user.consultantId
      }
    })

    if (isComponentUnmounted.value) return

    console.log('响应数据:', response.data)
    if (response.data.code === 200 && !isComponentUnmounted.value) {
      if (!response.data.data) {
        itemsArr.value = []
        total.value = 0
        ElMessage.warning('请先完成咨询师登记')
        return
      }
      itemsArr.value = response.data.data
      total.value = itemsArr.value.length
      isShow.value = true
    }
  } catch (error) {
    if (!isComponentUnmounted.value) {
      console.error('获取收费标准失败:', error)
      ElMessage.error('获取收费标准失败')
      itemsArr.value = []
      total.value = 0
    }
  } finally {
    if (!isComponentUnmounted.value) {
      isLoading.value = false
    }
  }
}

// 生命周期钩子
onUnmounted(() => {
  isComponentUnmounted.value = true
})

onMounted(async () => {
  isComponentUnmounted.value = false
  await loadAllFees()  // 在组件加载时就获取所有收费类型
  getFeeList()
})

// 添加收费标准
const addFee = async () => {
  try {
    if (!form.value.chargeTypeName || !form.value.price) {
      ElMessage.error('收费类型和价格不能为空')
      return
    }
    if (!form.value.chargeTypeId) {
      ElMessage.error('请从下拉列表中选择收费类型')
      return
    }

    let user = sessionStorage.getItem('user')
    if (!user) {
      ElMessage.error('请先登录')
      return
    }
    user = JSON.parse(user)

    // 修改重复检查逻辑
    const isDuplicate = itemsArr.value.some(item => 
      item.chargeTypeName === form.value.chargeTypeName ||  // 检查名称
      item.chargeTypeId === form.value.chargeTypeId         // 检查ID
    )
    if (isDuplicate) {
      ElMessage.warning(`已添加过"${form.value.chargeTypeName}"收费类型`)
      return
    }

    // 修改为新的接口和参数结构
    const params = {
      consultantId: user.consultantId,
      chargeTypeId: form.value.chargeTypeId,
      price: form.value.price
    }

    console.log('提交的数据:', params)  // 调试日志
    const response = await axios.get('consultants/insertChargeStandardAssociation', {
      params: params
    })
    
    if (response.data.code === 200) {
      ElMessage.success('添加成功')
      dialogFormVisible.value = false
      getFeeList()
      form.value = { chargeTypeId: '', chargeTypeName: '', price: '', consultantId: '' }
    } else {
      throw new Error(response.data.msg || '添加失败')
    }
  } catch (error) {
    console.error('添加失败:', error)
    ElMessage.error(error.message || '添加失败')
  }
}

// 处理删除
const handleDelete = async (chargeTypeId) => {
  try {
    let user = sessionStorage.getItem('user')
    console.log('原始用户数据:', user)

    if (!user) {
      ElMessage.error('请先登录')
      return
    }

    // 解析用户数据
    user = JSON.parse(user)
    console.log('解析后的用户数据:', user)
    
    // 获取要删除的收费标准信息
    const chargeTypeToDelete = itemsArr.value.find(item => item.chargeTypeId === chargeTypeId)
    if (!chargeTypeToDelete) {
      ElMessage.error('未找到要删除的收费标准')
      return
    }

    // 从所有收费类型中找到对应的ID
    const matchedType = allChargeTypes.value.find(
      type => type.chargeTypeName === chargeTypeToDelete.chargeTypeName
    )
    
    if (!matchedType) {
      ElMessage.error('未找到对应的收费类型')
      return
    }

    console.log('要删除的收费类型:', matchedType)

    await ElMessageBox.confirm('确定要删除该收费标准吗？', '提示', {
      type: 'warning'
    })
    
    const response = await axios.delete('consultants/deleteFeeManagementById', {
      params: {
        consultantId: user.consultantId,
        chargeTypeId: matchedType.chargeTypeId
      }
    })
    
    if (response.data.code === 200) {
      ElMessage.success('删除成功')
      getFeeList()
    } else {
      throw new Error(response.data.msg || '删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error)
      ElMessage.error(error.message || '删除失败')
    }
  }
}

// 分页处理
const handleSizeChange = async (size) => {
  pageSize.value = size
  currentPage.value = 1
  await getFeeList()
}

const handleCurrentChange = async (page) => {
  currentPage.value = page
  await getFeeList()
}

// 处理添加按钮点击
const handleAdd = async () => {
  let user = sessionStorage.getItem('user')
  if (!user) {
    ElMessage.error('请先登录')
    return
  }
  user = JSON.parse(user)

  // 检查咨询师是否已登记
  try {
    const checkResponse = await axios.get('consultants/selectAllFeeManagement', {
      params: {
        consultantId: user.consultantId
      }
    })
    
    if (!checkResponse.data.data) {
      ElMessage.warning('请先完成咨询师登记')
      return
    }
    
    await loadAllFees() // 获取最新的收费类型选项
    dialogFormVisible.value = true
  } catch (error) {
    console.error('检查失败:', error)
    ElMessage.error('系统错误，请稍后重试')
  }
}
</script>

<style scoped>
.inline-input {
  width: 100%;
}

:deep(.el-table) {
  margin-top: 20px;
}

:deep(.el-pagination) {
  margin-top: 20px;
  justify-content: center;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

.operation-group {
  display: flex;
  gap: 10px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style>
